<template>
    <div class="pagestyle">
        <el-row :gutter="20">
            <el-col :span="24">
                <div class="title_btn"><span @click="tozhiClick">知识库</span><span>/</span><span
                        style="font-weight: 700;">
                        {{state.titleListTypeName}}</span>
                </div>
            </el-col>
            <el-col :span="6">
                <div style="height: 78vh;" class="leftBoxList">
                    <el-avatar :size="100" style="margin-top: 40px;"
                        src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                    <p class="subTitle">{{router.currentRoute.value.query.name}}</p>
                    <div class="titleList">
                        <div class="titleListBox" @click="titleListTypeClick(item)"
                            :class="state.titleListType == item.value?'active':''" v-for="item in state.titleList">
                            <svg-icon style="margin-right: 10px;" class-name="search-icon" icon-class="jinru" />
                            {{ item.name }}
                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :span="18" style="width: 100%;height: 78vh; padding: 10px;
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.4);
            border: 1px solid rgba(229, 231, 235, 1);position: relative;">
                <p style="color: rgba(62, 70, 79, 1);font-size: 16px;
                font-weight: 700;">{{state.titleListTypeName}}</p>
                <p v-if="state.titleListType==1&&!state.chunkShow">数据解析成功后才能提问哦。</p>
                <p v-if="state.titleListType==2">最后一步！成功后，剩下的就交给小恒吧。</p>
                <p v-if="state.titleListType==3">在这里更新您的知识库详细信息，尤其是解析方法。</p>
                <div v-if="state.titleListType==1">
                    <div v-if="!state.chunkShow">
                        <p style="display: flex;justify-content: space-between;">
                            <span style="display: flex;">
                                <el-select @change="filesParseChange" v-model="state.value"
                                    :disabled="state.records.length==0" style="width: 100px;margin-right: 10px;">
                                    <el-option v-for="item in state.selList" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                                <el-input v-model="state.pageConfig.name" placeholder="搜索文件">
                                    <template #append>
                                        <span @click="searchClick">
                                            <svg-icon class-name="search-icon" icon-class="sousuo" />
                                            搜索
                                        </span>
                                    </template>
                                </el-input>
                            </span>
                            <el-upload class="upload-demo" action :show-file-list="false"
                                :http-request="uploadHttpRequestAdd">
                                <el-button type="primary">
                                    <svg-icon class-name="search-icon" icon-class="xinzeng" />
                                    新增文件
                                </el-button>
                            </el-upload>
                        </p>
                        <vxe-table border show-overflow ref="tableRef" :data="state.tableData"
                            @checkbox-change="checkboxChange">
                            <vxe-column type="checkbox" :width="50"></vxe-column>
                            <vxe-column title="名称">
                                <template #default="{ row }">
                                    <el-button type="text" @click="toKuaiClick(row)">{{ row.file_name }}</el-button>
                                </template>
                            </vxe-column>
                            <vxe-column field="chunk_count" title="分块数"></vxe-column>
                            <vxe-column field="create_date" title="上传日期">
                                <template #default="{ row }">
                                    {{ dayjs(row.create_date).format('YYYY-MM-DD hh:mm:ss') }}
                                </template>
                            </vxe-column>
                            <vxe-column field="parser_id" title="解析方法">
                            </vxe-column>
                            <vxe-column field="progress" title="解析状态">
                                <template #default="{ row }">
                                    <span style="display: flex;align-items: center;"
                                        v-if="row.file_id&&state.parsestatusList[row.file_id]">
                                        <el-popover :visible="state.progressvisible" placement="top" :width="160">
                                            <p><span style="font-weight: bold;margin-right: 10px;">开始于</span><span>
                                                    {{ state.parsestatusList[row.file_id].progress_start }}</span>
                                            </p>
                                            <p><span
                                                    style="font-weight: bold;margin-right: 10px;">持续时间</span><span>{{ state.parsestatusList[row.file_id].progress_duration }}</span>
                                            </p>
                                            <p><span
                                                    style="font-weight: bold;margin-right: 10px;">进度</span><span>{{ state.parsestatusList[row.file_id].progress_msg }}</span>
                                            </p>
                                            <template #reference>
                                                <el-tag @click="state.progressvisible = true"
                                                    :type="row.progress==1?'success':'warning'"
                                                    style="margin-right: 10px;">
                                                    {{row.progress==1?'成功':'未解析'}}</el-tag>
                                            </template>
                                        </el-popover>
                                        <el-popover :visible="state.parsevisible" placement="top" :width="160">
                                            <p>是否清空已有的23个chunk?</p>
                                            <div style="text-align: right; margin: 0">
                                                <el-button size="small" text @click="filesParseChange(2,row)">否
                                                </el-button>
                                                <el-button size="small" type="primary" @click="filesParseChange(1,row)">
                                                    是
                                                </el-button>
                                            </div>
                                            <template #reference>
                                                <svg-icon v-if="state.filesParseType==1" class="hover"
                                                    class-name="search-icon" icon-class="shuaxin-geejkf5n"
                                                    @click="state.parsevisible = true" />
                                                <svg-icon v-if="state.filesParseType==2" class="hover"
                                                    class-name="search-icon" icon-class="tubiaoneiguanbi2"
                                                    @click="state.parsevisible = true" />
                                            </template>
                                        </el-popover>

                                    </span>
                                </template>
                            </vxe-column>
                            <vxe-column title="动作" width="160">
                                <template #default="{ row }">
                                    <!-- <svg-icon class="hover" class-name="search-icon" icon-class="xiazai-geejkf58" /> -->
                                    <!-- <svg-icon class="hover" class-name="search-icon" icon-class="shezhi-geejkf58" /> -->
                                    <svg-icon @click="deletefileClick(row)" class="hover" class-name="search-icon"
                                        icon-class="shanchu-geejkf58" />
                                    <svg-icon @click="parseClick(row)" class="hover" class-name="search-icon"
                                        icon-class="bianji-geejkf79" />
                                </template>
                            </vxe-column>
                        </vxe-table>
                        <el-pagination style="position: absolute;right: 10px;
                        bottom: 20px;" class="globalFontSize"
                            v-model:current-page="state.pageConfig.page" v-model:page-size="state.pageConfig.per_page"
                            :page-sizes="[10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper"
                            :total="state.pageConfig.total" @size-change="pagechangeSize"
                            @current-change="pagechange" />
                    </div>
                    <div v-else style="height: 65vh;overflow-y: auto;">
                        <p>
                            <svg-icon @click="totitleListType" class-name="search-icon" icon-class="chexiao" />
                            <svg-icon class-name="search-icon" icon-class="xiangqing" />
                            {{ state.chunkTitle }}</p>
                        <div style="color: rgba(62, 70, 79, .6);font-size: 14px;margin: 10px 0;
                        border-bottom: 1px solid rgba(62, 70, 79, .2) ;padding: 10px;border-radius: 4px;" v-for="item in state.chunkList">
                            {{ item }}
                        </div>
                        <el-pagination style="position: absolute;right: 10px;
                        bottom: 20px;" class="globalFontSize"
                            v-model:current-page="state.pageConfigt.page" v-model:page-size="state.pageConfigt.per_page"
                            :page-sizes="[10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper"
                            :total="state.pageConfigt.total" @size-change="pagechangeSizet"
                            @current-change="pagechanget" />
                    </div>

                </div>
                <div v-if="state.titleListType==2">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form style="padding: 10px;" ref="formRef" :model="state.formDataparse"
                                :rules="state.rulesparse" label-position="top">
                                <el-form-item label="相似度阈值" prop="similarity_threshold">
                                    <el-slider :min='0' :max="20" v-model="state.formDataparse.similarity_threshold" />
                                </el-form-item>
                                <el-form-item label="关键字相似度权重" prop="vector_similarity_weight">
                                    <el-slider :min='0' :max="20"
                                        v-model="state.formDataparse.vector_similarity_weight" />
                                </el-form-item>
                                <el-form-item label="Rerank模型" prop="rerank_id">
                                    <el-select style="width: 100%;" clearable filterable
                                        v-model="state.formDataparse.rerank_id" placeholder="请选择">
                                        <el-option v-for="item in state.modelsList" :key="item.id" :label="item.id"
                                            :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item v-if="state.formDataparse.rerank_id" label="Top-K" prop="top_k">
                                    <el-slider :min='1' :max="2048" v-model="state.formDataparse.top_k" />
                                </el-form-item>
                                <el-form-item label="问题文本" prop="query">
                                    <el-input clearable v-model="state.formDataparse.query" placeholder="请输入你的问题">
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="">
                                    <el-button type="primary" @click="submitparseForm">
                                        确定
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-row>
                </div>
                <div v-if="state.titleListType==3">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form ref="formRef" :model="state.formDataconfig" :rules="state.rulesconfig"
                                label-position="top">
                                <el-form-item label="知识库名称" prop="name">
                                    <el-input clearable v-model="state.formDataconfig.name" placeholder="请输入">
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="解析方法" prop="chunk_method">
                                    <el-select style="width: 100%;" clearable filterable
                                        :disabled="state.formDataconfig.parse_status"
                                        v-model="state.formDataconfig.chunk_method" placeholder="请选择">
                                        <el-option v-for="item in [{label:'General',value:'naive'}]" :key="item.value"
                                            :label="item.label" :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="嵌入模型" prop="embedding_model">
                                    <el-select style="width: 100%;" clearable filterable
                                        :disabled="state.formDataconfig.parse_status"
                                        v-model="state.formDataconfig.embedding_model" placeholder="请选择">
                                        <el-option v-for="item in state.modelsList" :key="item.id" :label="item.id"
                                            :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="submitFormconfig">
                                        保存
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                        <el-col :span="16" style="color: rgba(62, 70, 79, 1);">
                            <p style="font-weight: bold;margin-bottom: 10px;">"General"分块方法说明</p>
                            <p>支持的文件格式为DOCX、EXCEL、PPT、IMAGE、PDF、TXT、MD、JSON、EML、HTML。此方法将简单的方法应用于块文件：·系统将使用视觉检测模型将连续文本分割成多个片段。接下来，这些连续的片段被合并成Token数不超过“Token数“的块。
                            </p>
                            <p style="font-weight: bold;margin-bottom: 10px;">"General"示例</p>
                            <p>支持的文件格式为DOCX、EXCEL、PPT、IMAGE、PDF、TXT、MD、JSON、EML、HTML。此方法将简单的方法应用于块文件：·系统将使用视觉检测模型将连续文本分割成多个片段。接下来，这些连续的片段被合并成Token数不超过“Token数“的块。
                            </p>
                        </el-col>
                    </el-row>
                </div>
            </el-col>
        </el-row>
        <!-- 新增弹框 -->
        <teleport to="body">
            <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto"
                v-model="state.addModal" resize :mask="true" showFooter>
                <template #title>
                    <div class="w100 h100 fsc mask_title">解析方法</div>
                </template>
                <template #default>
                    <div class="form_box">
                        <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
                            <el-form-item label="解析方法" prop="chunk_method">
                                <el-select clearable filterable v-model="state.formData.chunk_method" placeholder="请选择">
                                    <el-option v-for="item in [{label:'General',value:'naive'}]" :key="item.value"
                                        :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="重命名" prop="name">
                                <el-input clearable v-model="state.formData.name" placeholder="请输入"></el-input>
                            </el-form-item>
                            <el-form-item label="块Token数" prop="chunk_token_num">
                                <el-slider style="margin-left: 5px;" :min='0' :max="2048"
                                    v-model="state.formData.chunk_token_num" show-input />
                            </el-form-item>
                            <el-form-item label="分段标识符" prop="delimiter">
                                <el-input clearable v-model="state.formData.delimiter" placeholder="请输入"></el-input>
                            </el-form-item>
                            <el-form-item label="层次识别">
                                <el-switch v-model="state.formData.layout_recognize" />
                            </el-form-item>
                            <el-form-item label="使用召回增强RAPTOR策略">
                                <el-switch v-model="state.formData.raptor" />
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #footer>
                    <el-button @click="cancelform">取消</el-button>
                    <el-button type="primary" @click="submitForm">
                        确定
                    </el-button>
                </template>
            </vxe-modal>
        </teleport>
    </div>
</template>
<script setup>
    import {
        computed,
        reactive
    } from "vue";
    import axios from "axios"
    import dayjs from "dayjs";
    import {
        ElMessageBox
    } from 'element-plus'
    const {
        proxy
    } = getCurrentInstance();
    const router = useRouter();
    let state = reactive({
        parsevisible: false,
        tableData: [],
        value: '批量',
        selList: [{
            label: '解析',
            value: 1
        }, {
            label: '取消',
            value: 2
        }, {
            label: '删除',
            value: 3
        }],
        titleListType: 1,
        titleListTypeName: "数据集",
        titleList: [{
            value: 1,
            name: '数据集',
            icon: 'jinru'
        }, {
            value: 2,
            name: '检索测试',
            icon: ' jinru'
        }, {
            value: 3,
            name: '配置',
            icon: ''
        }],
        search: '',
        addvisible: false,
        systemName: '',
        records: [],
        addModal: false,
        formData: {
            layout_recognize: false,
            raptor: false,
            chunk_method: "General"
        },
        rules: {
            chunk_method: [{
                required: true,
                message: '请选择解析方法',
                trigger: 'change'
            }],
            name: [{
                required: true,
                message: '请输入重命名',
                trigger: 'blur'
            }],
            delimiter: [{
                required: true,
                message: '请输入分段标识符',
                trigger: 'blur'
            }]
        },
        filesParseType: 1,
        formDataparse: {
            similarity_threshold: 0,
            vector_similarity_weight: 0,
            top_k: 1
        },
        rulesparse: {},
        // 块级显示
        chunkShow: false,
        chunkList: [],
        chunkTitle: '',
        // 配置页面
        formDataconfig: {},
        rulesconfig: {},
        modelsList: [],
        progressvisible: false,
        parsestatusList: {},
        pageConfig: {
            page: 1,
            per_page: 10,
            total: 0,
            name: ''
        },
        pageConfigt: {
            page: 1,
            per_page: 10,
            total: 0
        }
    })

    function parsestatusList() {
        axios.post('/chat-api/files/parse_status', {
                dataset_id: router.currentRoute.value.query.id
            })
            .then(res => {
                state.parsestatusList = res.data.parse_status
            })
    }

    parsestatusList()

    function submitparseForm() {
        state.formDataparse.file_ids = state.tableData.map(item => {
            return item.file_id
        })
        state.formDataparse.dataset_id = router.currentRoute.value.query.id
        axios.post('/chat-api/dataset/retrieve', state.formDataparse).then(res => {
            if (res.status == 'success') {
                state.addvisible = false
            }
        })

    }

    // 获取块级列表
    // 接口
    function getchunks(){
        axios.post('/chat-api/file/chunks', {
            dataset_id: router.currentRoute.value.query.id,
            file_id: state.pageConfigt.file_id,
            page: state.pageConfigt.page,
            per_page: state.pageConfigt.per_page
        }).then(res => {
            if (res.data.status == 'success') {
                state.chunkList = res.data.chunks
                state.pageConfigt.total=res.data.total_chunks
            }
        })
    }
    function toKuaiClick(row) {
        state.pageConfigt.file_id=row.file_id
        state.chunkTitle = row.file_name
        state.chunkShow = true
        getchunks()
    }
    function pagechangeSizet(val){
        state.pageConfigt.page=1
        state.pageConfigt.per_page=val
        getchunks()
    }
    function pagechanget(val){
        state.pageConfigt.page=val
        getchunks()
    }
    // 搜索按钮
    function searchClick(){
        getdatasetList()
    }
    // 分页
    function pagechangeSize(val){
        state.pageConfig.page=1
        state.pageConfig.per_page=val
        getdatasetList()
    }
    function pagechange(val){
        state.pageConfig.page=val
        getdatasetList()
    }
    // 返回
    function totitleListType() {
        state.titleListType = 1
        state.chunkShow = false
    }

    async function getdatasetList(id) {
        await axios.post('/chat-api/files/list', {
            dataset_id: router.currentRoute.value.query.id,
            page: state.pageConfig.page,
            per_page: state.pageConfig.per_page,
            name: state.pageConfig.name
        }).then(async res => {
            state.tableData = res.data.files
            state.pageConfig.total=res.data.total_files
        })
    }

    function uploadHttpRequestAdd(data) {
        const formData = new FormData();
        formData.append("file", data.file);
        formData.append("dataset_id", router.currentRoute.value.query.id);
        axios.post('/chat-api/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => {
            getdatasetList(router.currentRoute.value.query.id)
        })
    }

    function tozhiClick() {
        router.push('/knowledgeAiChat/know_knowledgebase')
    }

    function titleListTypeClick(type) {
        state.titleListType = type.value
        state.titleListTypeName = type.name
        if (type.value == 2) {
            getmodels('reranker')
        } else if (type.value == 3) {
            getmodels('embedding')
            getconfigdataset()
        }
    }
    // 获取配置页面详情
    function getconfigdataset() {
        axios.get('/chat-api/dataset?dataset_id=' + router.currentRoute.value.query.id).then(res => {
            state.formDataconfig = res.data.config
        })
    }
    getdatasetList(router.currentRoute.value.query.id)

    function checkboxChange(e) {
        state.records = e.records
    }

    function deletefileClick(row) {
        let ids = []
        if (row) {
            ids = [row.file_id]
        } else {
            ids = state.records.map(item => {
                return item.file_id
            })
        }
        ElMessageBox.confirm('确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            axios.post('/chat-api/delete_files', {
                file_ids: ids,
                dataset_id: router.currentRoute.value.query.id
            }).then(res => {
                getdatasetList(router.currentRoute.value.query.id)

            })
        }).catch(() => {});

    }

    function filesParseChange(val, row) {
        let ids = []
        if (row) {
            ids = [row.file_id]
        } else {
            ids = state.records.map(item => {
                return item.file_id
            })
        }
        if (val == 1) {
            axios.post('/chat-api/files/parse', {
                file_ids: ids,
                dataset_id: router.currentRoute.value.query.id
            }).then(res => {
                state.filesParseType = 2
                proxy.$modal.msgSuccess(res.data.message);
                getdatasetList(router.currentRoute.value.query.id)
                state.parsevisible = false
            }).catch(() => {
                state.parsevisible = false
            })
        }
        if (val == 2) {
            axios.post('/chat-api/files/unparse', {
                file_ids: ids,
                dataset_id: router.currentRoute.value.query.id
            }).then(res => {
                state.filesParseType = 1
                proxy.$modal.msgSuccess(res.data.message);
                getdatasetList(router.currentRoute.value.query.id)
                state.parsevisible = false
            }).catch(() => {
                state.parsevisible = false
            })
        }
        if (val == 3) {
            ElMessageBox.confirm('确定要删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.post('/chat-api/delete_files', {
                    file_ids: state.records.map(item => {
                        return item.file_id
                    }),
                    dataset_id: router.currentRoute.value.query.id
                }).then(res => {

                })
            }).catch(() => {});
        }
    }

    function parseClick(row) {
        state.addModal = true
        state.formData.file_id = row.file_id
    }

    function cancelform() {
        state.addModal = false
    }

    function submitForm() {
        state.formData.dataset_id = router.currentRoute.value.query.id
        proxy.$refs["formRef"].validate(valid => {
            if (valid) {
                axios.post('/chat-api/files', state.formData).then(res => {
                    if (res.data.status == 'success') {
                        state.addModal = false
                        getdatasetList(router.currentRoute.value.query.id)
                    }
                })
            }
        })
    }
    // 提交配置页面
    function submitFormconfig() {
        state.formDataconfig.dataset_id = router.currentRoute.value.query.id
        axios.post('/chat-api/dataset', state.formDataconfig).then(res => {

        })
    }
    // 获取rank模型和嵌入模型下拉数据
    function getmodels(data) {
        axios.get('/chat-api/models?sub_type=' + data).then(res => {
            state.modelsList = res.data.models.data
        })
    }
</script>
<style scoped lang="scss">
    .mb {
        margin-bottom: 10px;
    }

    :deep(.el-input-group__append, .el-input-group__prepend) {
        background-color: #409eff;
        color: #fff;
    }

    .pagestyle {
        border-radius: 8px;
        background: rgba(255, 255, 255, 0.6);
        box-shadow: 0px 0px 16px rgba(0, 0, 0, 0.12);
        padding: 15px 16px;

        .leftBoxList {
            padding: 10px;
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.4);
            border: 1px solid rgba(229, 231, 235, 1);
            color: rgba(62, 70, 79, 1);
            text-align: center;

            .subTitle {
                margin-top: 20px;
                font-size: 16px;
                font-weight: 700;
            }

            .titleList {
                margin-top: 20px;
                text-align: left;

                .titleListBox {
                    padding: 8px 16px 8px 16px;
                    border-radius: 2px;
                    cursor: pointer;

                    &.active {
                        background: rgba(91, 109, 128, 0.08);
                    }
                }
            }
        }

        .title_btn {
            padding-bottom: 10px;
            font-size: 18px;
            color: rgba(62, 70, 79, 1);
            display: flex;
            align-items: center;
        }

        .ca_title {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .titleText {
            margin-top: 20px;
            font-size: 20px;
            color: rgba(62, 70, 79, 1);
            font-weight: 500;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
        }

        .subTitle {
            margin: 0;
            padding: 0;
            margin-top: 10px;
            color: rgba(51, 51, 51, 1);
            font-size: 14px;
            font-weight: 500;

        }
    }
</style>